<?php

namespace backend\controllers;

use common\logic\OrderStatus;
use common\models\OrderStatusFlow;
use Yii;
use backend\models\Order;
use common\logic\Order as OrderLogic;
use backend\models\OrderSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrderController extends Controller {
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Order models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new OrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        Yii::$app->user->setReturnUrl(Yii::$app->request->getUrl());
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Order model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id) {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Order model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Order();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect([
                'view',
                'id' => $model->id
            ]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionPlatformConfirm($id) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = $this->findModel($id);
        $r = OrderLogic::platformConfirm($model->order_id);
        if ($r['err'] == 0) {
            Yii::$app->session->addFlash('success', '操作成功');
        } else {
            Yii::$app->session->addFlash('warning', $r['msg']);
        }
        $this->redirect(\yii\helpers\Url::to([
            'update',
            'id' => $id
        ]));
    }

    public function actionSupplyConfirm($id) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = $this->findModel($id);
        $r = OrderLogic::supplierConfirm($model->order_id);
        if ($r['err'] == 0) {
            Yii::$app->session->addFlash('success', '操作成功');
        } else {
            Yii::$app->session->addFlash('warning', $r['msg']);
        }
        $this->redirect(\yii\helpers\Url::to([
            'update',
            'id' => $id
        ]));
    }

    /**
     * 退款
     */
    public function actionRefund($id) {
        $model = $this->findModel($id);
        $order = \common\logic\Order::getOrderAdmin($model->order_id);
        $res = \common\logic\Order::platformRefundManually($order);
        if ($res['err'] == 0) {
            Yii::$app->session->addFlash('success', '操作成功');
        } else {
            Yii::$app->session->addFlash('warning', $res['msg']);
        }
        $this->redirect(\yii\helpers\Url::to([
            'update',
            'id' => $id
        ]));
    }

    public function actionRemitting($id) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = $this->findModel($id);
        $r = OrderLogic::remitToSupplier($model->order_id);
        if ($r['err'] == 0) {
            Yii::$app->session->addFlash('success', '操作成功');
        } else {
            Yii::$app->session->addFlash('warning', $r['msg']);
        }
        $this->redirect(\yii\helpers\Url::to([
            'update',
            'id' => $id
        ]));
    }
    public function actionRemitted($id){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $model = $this->findModel($id);
        $r = OrderLogic::supplierRemittanceReceived($model->order_id);
        if ($r['err'] == 0) {
            Yii::$app->session->addFlash('success', '操作成功');
        } else {
            Yii::$app->session->addFlash('warning', $r['msg']);
        }
        $this->redirect(\yii\helpers\Url::to([
            'update',
            'id' => $id
        ]));
    }

    /**
     * Updates an existing Order model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        $ext = json_decode($model->ext, true);
        $flow = OrderStatusFlow::getList("order_id='{$model->order_id}'", '*', 'ctime ASC');
        $flows = [];
        foreach ($flow as $k => $v) {//按ctime聚合
            $flows[$v['ctime']][$v['type']] = $v['status'];
            empty($flows[$v['ctime']]['ctime']) && $flows[$v['ctime']]['ctime'] = $v['ctime'];
            empty($flows[$v['ctime']]['reason']) && $flows[$v['ctime']]['reason'] = $v['reason'];
            //$flows[$v['ctime']]['reason'][] = $v['reason'];
        }
        $formData = Yii::$app->request->post()[$model->formName()]??[];
        $data = [];
        if ($formData) {
            $ext['clientEnName'] = [
                $formData['first_name'],
                $formData['last_name']
            ];
            $data[$model->formName()] = [
                //'contact' => $formData['contact'],
                'email' => $formData['email'],
                'phone' => $formData['phone'],
                'use_protect' => $formData['use_protect'],
                'message' => $formData['message'],
                'payment' => $formData['payment'],
                'ext' => json_encode($ext, JSON_UNESCAPED_UNICODE),
            ];
        }
        $model->load($data) && $model->save();
        $model->first_name = $ext['enClientName'][0];
        $model->last_name = $ext['enClientName'][1];
        //Occupancy::chooseOccupancy($model->trip_id,$model->cabin_id, $model->one_self);
        return $this->render('update', [
            'model' => $model,
            'flow' => array_values($flows),
        ]);
    }

    /**
     * Deletes an existing Order model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id) {
        $m = $this->findModel($id);
        $m->deleted = \common\models\Order::DELETED;
        $m->update();
        return $this->redirect(['index']);
    }

    /**
     * Finds the Order model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Order::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
